<template>
  <div>
    <!-- 卡片一 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>商品(Sku)介绍</h3>
        </div>
      </template>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="addlist.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="初始价格" prop="originalPrice">
          <el-input v-model="addlist.originalPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="price">
          <el-input v-model="addlist.price">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPrice">
          <el-input v-model="addlist.vipPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="Inventory">
          <el-input
            autocomplete="off"
            disabled
            v-model="addlist.Inventory"
          ></el-input>
        </el-form-item>
        <el-form-item label="运费模版" prop="pass">
          <el-cascader
            placeholder="请选择"
            :options="freightdata"
            :props="freightprops"
            clearable
            v-model="addlist.freightTemplateId"
          />
        </el-form-item>
        <el-form-item label="是否在售" prop="pass">
          <el-radio v-model="addlist.status" :label="1" size="large"
            >在售</el-radio
          >
          <el-radio v-model="addlist.status" :label="0" size="large"
            >下单</el-radio
          >
        </el-form-item>
        <el-form-item label="商品图片" prop="pass">
          <el-upload
            :action="addback + '/upload/admin'"
            list-type="picture-card"
            :on-success="lsit"
            :file-list="fileList"
            :headers="requestimg"
            :limit="5"
            :on-exceed="hook"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="addlist.imgList" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品单位" prop="unit">
          <el-input
            v-model="addlist.unit"
            autocomplete="off"
            placeholder=" 件 / 个 / 盒"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属类目" prop="pass">
          <el-cascader
            v-model="addlist.categoryId"
            :options="categorydata"
            :props="categorprops"
            placeholder="请选择类目"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品简介" prop="pass">
          <el-input
            v-model="addlist.description"
            autocomplete="off"
            placeholder="商品简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="pass">
          <Richtext v-model="addlist.detail"></Richtext>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 卡片二 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>商品参数</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="add()">添加</el-button>
      <el-table :data="addlist.attributeList" style="width: 100%">
        <el-table-column prop="attribute" label="商品参数名称" />
        <el-table-column prop="value" label="商品参数值" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="CommoditiesDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 卡片三 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>规格维度</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="adds()">添加</el-button>
      <el-table :data="addlist.specificationList" style="width: 100%">
        <el-table-column prop="date" label="维度ID" />
        <el-table-column prop="title" label="维度名称" />
        <el-table-column prop="gmtCreate" label="创建时间">
          <template #default="scope">
            {{ new Date(scope.row.gmtCreate).friendtTime() }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="modifies(scope.row, scope.$index)"
              >修改</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deletetwo(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 卡片四 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>商品(sku)详情</h3>
        </div>
      </template>
      <el-button type="primary" plain @click="lotsize()">批量定价</el-button>
      <div
        class="tag"
        v-for="(item, index) in addlist.specificationList"
        :key="index"
      >
        <span
          ><el-tag>{{ item.title }}</el-tag></span
        >
        <el-tag
          v-for="tag in item.values"
          :key="tag"
          class="mx-1"
          closable
          :disable-transitions="false"
          @close="tagDelete(tag, index)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="item.inputSkuTagVisible"
          ref="InputRef"
          v-model="item.inputSkuTagValue"
          class="input-new-tag"
          size="small"
          @keyup.enter="handleInputConfirm(item.inputSkuTagValue, index)"
          @blur="handleInputConfirm(item.inputSkuTagValue, index)"
        />
        <el-button
          v-else
          class="button-new-tag ml-1"
          size="small"
          @click="addInput(index)"
        >
          添加
        </el-button>
      </div>
      <!-- sku表格 -->
      <el-table
        :data="addlist.skuList"
        border
        :span-method="(...arg) => strategySpanMethod(...arg, addlist.skuList)"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column
          v-for="item in addlist.specificationList"
          :key="item.id"
          :prop="'id_' + item.title"
          :label="item.title"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="" label="Skuid" width="180" />
        <el-table-column prop="price" label="￥价格(元)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.price"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column prop="vipPrice" label="￥VIP价(元)" width="180px">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.vipPrice"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="originalPrice"
          label="￥吊牌价(元)"
          width="180px"
        >
          <template #default="scope">
            <el-input-number
              v-model="scope.row.originalPrice"
              :precision="2"
              :step="1"
            />
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存(件)" width="180px">
          <template #default="scope">
            <el-input-number v-model="scope.row.stock" />
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量(克)" width="180px">
          <template #default="scope">
            <el-input-number v-model="scope.row.weight" />
          </template>
        </el-table-column>
        <el-table-column prop="img" label="sku图片" width="80">
          <template #default="scope">
            <el-upload
              class="avatar-uploader"
              action="/upload/admin"
              :show-file-list="false"
              :on-success="handleAvatar"
              :headers="requestimg"
            >
              <img :src="scope.row.img" class="avatar" v-if="scope.row.img" />
              <el-icon
                v-else
                class="avatar-uploader-icon"
                @click="show(scope.$index)"
              >
                <Plus />
              </el-icon>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column prop="barCode" label="条形码" width="180">
          <template #default="scope">
            <el-input v-model="scope.row.barCode" style="width: 200px">
              <template #append>
                <div @click="timeStamp(scope.$index)">随机</div>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div class="botton">
        <el-button plain @click="handleCloses()">取消</el-button
        ><el-button type="primary" @click="addEss()">保存商品</el-button>
      </div>
    </el-card>
    <!-- 商品参数对话框 -->
    <el-dialog v-model="adddialogVisible" :title="CommoditiesTitle" width="30%">
      <el-form
        ref="addruleForm"
        :model="addCommodities"
        :rules="commodities"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model.trim="addCommodities.attribute" />
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model.trim="addCommodities.value" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adddialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addsure('addruleForm')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 规格添加对话框 -->
    <el-dialog
      v-model="cationdialogue"
      :title="Specificationstitle"
      width="30%"
    >
      <el-form
        ref="Specifi"
        :model="addSpecifications"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model.trim="addSpecifications.title" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cationdialogue = false">取消</el-button>
          <el-button type="primary" @click="Specificationsure('Specifi')"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 批量定价对话框 -->
    <el-dialog v-model="lotsizedialog" title="批量定价" width="30%">
      <el-form
        ref="ruleFormRef"
        :model="lotsizedialog"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
      >
        <el-form-item label="现价(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.price"
            :precision="2"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="VIP价格(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.vipPrice"
            :precision="2"
            :step="1"
          />
        </el-form-item>
        <el-form-item label="吊牌价格(￥)" prop="name">
          <el-input-number
            v-model="lotPricing.originalPrice"
            :precision="2"
            :step="1"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="lotsizedialog = false">取消</el-button>
          <el-button type="primary" @click="lotsizesure()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import http from "@/http";
import host from "@/http";
import cookie from "js-cookie";
import { ElMessage } from "element-plus";
import Richtext from "@/components/Richtext/Richtext";
export default {
  components: {
    Richtext,
  },
  data() {
    return {
      num: 20,
      skuIndex: "",
      //邮费
      freightdata: [],
      freightprops: {
        children: "childrenList",
        label: "title",
        value: "id",
        checkStrictly: true,
        emitPath: false,
      },
      //商品类目
      categorydata: [],
      categorprops: {
        children: "childrenList",
        emitPath: false,
        label: "title",
        value: "id",
      },
      //商品参数对话框
      adddialogVisible: false,
      CommoditiesTitle: "",
      //商品参数
      addCommodities: {
        attribute: "",
        value: "",
      },
      //规格维度
      addSpecifications: {
        title: "",
        values: [],
        gmtCreate: null,
        gmtUpdate: null,
        inputSkuTagVisible: false,
        inputSkuTagValue: "",
      },
      //规格添加对话框
      cationdialogue: false,
      Specificationstitle: "",

      //批量定价
      lotsizedialog: false,

      //批量定价
      lotPricing: {
        originalPrice: 0, //原价格
        price: 0, //现价
        vipPrice: 0, //vip价格
      },
      stock: 1, //库存
      img: "", //sku图片
      weight: 1, //重量
      barCode: "", //条形码

      commodities: {
        attribute: [
          { required: true, message: "请输入参数名称！", trigger: "blur" },
        ],
        value: [{ required: true, message: "请输入参数值！", trigger: "blur" }],
      },
      //添加数据
      addlist: {
        title: "前端it程序员", //标题
        price: 260, //现在价格
        originalPrice: 300, //初始价格
        vipPrice: 200, //会员价格
        freightTemplateId: "", //邮费类目
        status: 1, // 1 在售 0 未售
        imgList: [], //图片数组
        description: "你好的",
        categoryId: "", //所属类目
        detail: "", //
        unit: "",
        img: "",
        Inventory: 0,
        attributeList: [], //商品参数
        specificationList: [], //规格维度
        skuList: [], //sku表格
      },
    };
  },
  created() {
    this.freight();
    this.category();
    this.requestimg = {
      AdminToken: cookie.get("token"),
    };
  },
  computed: {
    action() {
      return host.host;
    },
  },
  methods: {
    //运费
    freight() {
      let freightlist = {
        _gp: "admin.freight",
        _mt: "list",
      };
      http.post(freightlist).then((res) => {
        this.freightdata = res.data;
      });
    },
    //类目树
    category() {
      let categorylist = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      http.post(categorylist).then((res) => {
        this.categorydata = res.data;
      });
    },
    //商品图片上传
    lsit(res) {
      let url = res.url;
      this.addlist.imgList.push(url);
    },
    //超出图片限制钩子
    hook() {
      ElMessage.warning("最多上传五张图片！");
    },
    //商品参数添加
    add() {
      (this.CommoditiesTitle = "添加"), (this.addCommodities = {});
      this.adddialogVisible = true;
    },
    //商品删除
    CommoditiesDelete(index, row) {
      this.addlist.attributeList.splice(index, 1);
    },
    //商品添加确定
    addsure() {
      this.addlist.attributeList.push(this.addCommodities);
      ElMessage.success("添加成功！");
      this.adddialogVisible = false;
    },
    //关闭
    handleCloses() {
      this.$store.state.tagmodules.taglist.splice(
        this.$store.state.tagmodules.index,
        1
      );
      this.$router.push({ name: "something" });
    },
    //规格添加
    adds() {
      this.addSpecifications = {};
      this.Specificationstitle = "添加";
      this.cationdialogue = true;
    },
    modifies(row, index) {
      this.Specificationstitle = "修改";
      this.cationdialogue = true;
      Object.assign(this.addSpecifications, {
        title: row.title,
        gmtCreate: row.gmtCreate,
        gmtUpdate: row.gmtUpdate,
        index, //传个索引下去
      });
    },
    //规格维度确定
    Specificationsure() {
      if (this.Specificationstitle == "添加") {
        this.addlist.specificationList.push({
          title: this.addSpecifications.title,
          gmtCreate: Date.now(),
          gmtUpdate: Date.now(),
          values: [],
          inputSkuTagVisible: false,
          inputSkuTagValue: "",
        });
        this.cationdialogue = false;
      } else {
        this.addlist.specificationList[this.addSpecifications.index].title =
          this.addSpecifications.title;
        this.cationdialogue = false;
      }
    },
    //删除tag标签触发
    tagDelete(tag, index) {
      // console.log(tag) 当前元素值
      let add = this.addlist.specificationList[index].values;
      add.splice(add.indexOf(tag), 1);
      this.shows();
    },
    //添加追加标签
    addInput(index) {
      // console.log(index)
      this.addlist.specificationList[index].inputSkuTagVisible = true;
      this.shows();
    },
    //键盘回车触发
    handleInputConfirm(item, index) {
      // console.log(item,index);
      let data = this.addlist.specificationList;
      if (item) {
        data[index].values.push(item);
      }
      data[index].inputSkuTagVisible = false;
      data[index].inputSkuTagValue = "";
      this.shows();
    },
    shows() {
      let chicun = [];
      this.addlist.specificationList.forEach((val) => {
        //data是规格维度的数组
        chicun.push(val.values); //拿到values数组的值放到新数组
      });
      //笛卡尔积算法  chicun ==  values数组
      let dier = chicun.reduce(
        (total, list) => {
          //total, list 不传初始值就是数组第一二项
          let chicunlist = [];
          total.forEach((item) => {
            list.forEach((val) => {
              chicunlist.push(item.concat(val));
            });
          });
          return chicunlist; // console.log(chicunlist); //尺寸和颜色的累计
        },
        [[]] //已经传了初始值数组
        //得到累加的值
      );

      if (this.addlist.specificationList.length > 0) {
        //判断规格数组的长度,大于1的时候就把处理的放入进去
        this.addlist.skuList = [];
        dier.forEach((item) => {
          //累加的值遍历
          let kals = {
            price: this.lotPricing.price,
            vipPrice: this.lotPricing.vipPrice,
            originalPrice: this.lotPricing.originalPrice,
            stock: 0,
            weight: 0,
            img: "",
          };
          //规格维度
          this.addlist.specificationList.forEach((val, index) => {
            // console.log(val);
            //拿到维度数组然后给新的数组新增一个数据
            kals["id_" + val.title] = item[index]; //计算出来的全部值1
          });
          this.addlist.skuList.push(kals);
          // //然后丢到那个sku表格数组
        });
      } else {
      }
      //要给表格进行处理
      //数组新增二个元素：title,specification
      this.addlist.skuList.forEach((item) => {
        // console.log(item); //sku表格对象
        let titleData = [];
        let specificationData = [];
        for (const key in item) {
          if (0 <= key.indexOf("id_")) {
            titleData.push(item[key]);
            specificationData.push(key.slice(3) + "_" + item[key]);
          }
        }
        //给数组加了二个参数然后分割
        item["title"] = titleData.join();
        item["specification"] = specificationData.join();
      });
    },
    //计算表格行列

    //sku图片添加的下标
    show(index) {
      this.skuIndex = index;
    },
    //sku成功的回调
    handleAvatar(res) {
      this.addlist.skuList[this.skuIndex].img = res.url;
    },
    //随机条形码
    timeStamp(index) {
      let time = +new Date();
      this.addlist.skuList[index].barCode = time;
    },
    //批量定价
    lotsize() {
      this.lotsizedialog = true;
    },
    strategySpanMethod: function (
      { row, column, rowIndex, columnIndex },
      data
    ) {
      let index = this.addlist.specificationList.length;
      // data 就是从这里动态传过来的, column.property是表头的key
      if (index > columnIndex) {
        var spanArr = this.getSpanArr(data, column.property);
        const _row = spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },

    getSpanArr: function (data, spanKey) {
      var that = this;
      var spanArr = [];
      var pos = "";
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          spanArr.push(1);
          pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i][spanKey] === data[i - 1][spanKey]) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }
      }
      return spanArr;
    },

    //批量定价确定
    lotsizesure() {
      let dinner = this.lotPricing;
      this.addlist.skuList.forEach((item) => {
        item.price = dinner.price;
        item.originalPrice = dinner.originalPrice;
        item.vipPrice = dinner.vipPrice;
      });
      this.lotsizedialog = false;
    },
    //确定按钮
    addEss(index) {
      this.addlist.img = this.addlist.imgList[0];
      let data = {
        _gp: "admin.product",
        _mt: "create",
        spuDTO: JSON.stringify(this.addlist),
      };
      http.post(data).then((res) => {
        if (200 == res.errno) {
          // this.$routr.push({name:"commod"})
          ElMessageBox.confirm("创建成功,是否继续添加？", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "success",
          })
            .then(() => {})
            .catch(() => {
              ElMessage({
                type: "error",
                message: "已取消,跳转回商品列表页面",
              });
              this.$router.push({ name: "something" });
            });
          // ElMessage.success("创建成功！");
          // this.$router.push({ name: "something" });
        } else {
          ElMessage.error(res.errmsg);
        }
      });
    },
  },
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 40px;
  height: 40px;
  display: block;
}
</style>
<style lang="less" scoped>
h3 {
  padding: 0px;
  margin: 0px;
  margin-left: 18px;
}
.botton {
  margin-top: 20px;
}
.el-card /deep/ .el-card__header {
  border: none;
  padding: 0px;
  margin-top: 15px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  border: 1px solid #ccc;
}

.tag {
  margin-top: 20px;
  .el-tag {
    margin-right: 8px;
  }
  .mx-1 {
    margin-right: 5px;
  }
  .input-new-tag {
    width: 90px;
    vertical-align: bottom;
  }
}
</style>
